{% extends "base-user.html" %}

{% block css%}
<link href="/static/css/morris/morris.css" rel="stylesheet" type="text/css" />    
{% endblock %}
{% block js%}  
<script src="/static/js/plugins/raphael-min.js"></script>
<script src="/static/js/plugins/morris/morris.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
    // {% if count > 0 %}
    //     $('#btn-{{ device_all.0.id }}').click();
    // {% endif %}
})
function edit_device(id){
    window.location.href=("{% url 'PiApp.views.edit_device_view' %}?device_id=" + id);
}
function remove_device(get_id){
    if(confirm('Sure?')) {
        $.getJSON("/API/device/"  +  get_id  + "/remove",  {}, 
            function(data){
                if(data['msg'] != 'ok') {
                    alert('failed');
                } else {
                    window.location.href=("");  
                }                  
        });
    }
}
function get_data(get_id){
    $.getJSON("/API/device/" + get_id ,  {device_id : get_id}, 
        function(data){
            if(data['msg'] != 'ok') {
                alert('failed');
            } else {

                var content = data['title'] + '<small>' + data['about'] + '</small> ';
                $('#device-name').html(content);
                $('#device-name').attr("data-id", get_id);
                content = data['x']  + '%';
                $('#device-x').html(content);
                content = data['y']  + '%';
                $('#device-y').html(content);
                content = data['location'];
                $('#device-location').html(content);
                $('#device-body').css('display', 'block');

                content = '<button class="btn btn-default" onclick="edit_device('
                content += get_id + ')"><i class="fa fa-edit"></i></button>'
                content += '<button class="btn btn-default" onclick="remove_device(' + get_id + ')"><i class="fa fa-minus"></i></button>'
                    
                $('#device-btn').html(content);
                content = data['id'];
                $('#device-id').html(content);
                get_sensor(get_id);

            }                  
    });
}
function add_sensor(){
    id = $('#device-name').attr("data-id");
    window.location.href=("{% url 'PiApp.views.add_sensor_view' %}?device_id=" + id);
}
function get_sensor(get_id){
    $.getJSON("/API/device/" + get_id + "/sensor",  { }, 
        function(data){
            if(data['msg'] != 'ok') {
                alert('get sensor failed');
            } else {
                if(data['sensor'].length == 0)
                    $('.alert').css("display", "block"); 
                $('#sensor-content').html("");
                for(var i=0; i<data['sensor'].length; i++){ 
                    var content = get_sensor_content(data['sensor'][i]);
                    $('#sensor-content').append(content);
                    if(data['sensor'][i]['type'] == 's'){
                        switch_refresh(data['sensor'][i]['id']);
                        callback_refresh(data['sensor'][i]['id']);
                    } else if(data['sensor'][i]['type'] == 'n'){
                        curvet_refresh(data['sensor'][i]['id'], data['sensor'][i]['unit']);
                        callback_refresh(data['sensor'][i]['id']);
                    } else if(data['sensor'][i]['type'] == 'p'){
                        img_refresh(data['sensor'][i]['id']);
                    }                
                }  
            }                  
    });
}
function get_sensor_content(sensor){
    var content = '<div class="callout callout-info"><div class="row"><div class="col-md-2">'
    
    if(sensor['type'] == 's') {
        content += '<img src="/static/img/sensor-switch.png"></img><div style="padding-top:8px;padding-bottom:8px;">'
    } else if(sensor['type'] == 'n') {
        content += '<img src="/static/img/sensor-numeric.png"></img><div style="padding-top:8px;padding-bottom:8px;">'
    } else if(sensor['type'] == 'p') {
        content += '<img src="/static/img/sensor-picture.png"></img><div style="padding-top:8px;padding-bottom:8px;">'        
    }

    content += '<b>' + sensor['name'] + '</b></div><div id="sensor-btn" class="btn-group">'
    content += '<button class="btn btn-primary btn-sm" onclick="edit_sensor(' + sensor['id'] + ')"><i class="fa fa-edit"></i></button>'
    content += '<button class="btn btn-primary btn-sm" onclick="remove_sensor(' + sensor['id'] + ')"><i class="fa fa-minus"></i></button>'
    content += '</div><div style="padding-top:8px;padding-bottom:8px;">'
    content += '<p>' + sensor['describe'] + '</p>'
    content += '<b>SensorId:' + sensor['id'] + '</b>'
    content += '</div></div>'
    content += '<div class="col-md-10">'

    content += '<div class="box box-primary">'   

    if(sensor['type'] == 's') {
        content += '<div class="box-header"><h3 class="box-title">Switch</h3></div>'
        content += '<div class="box-body"><center><div class="btn-group" data-toggle="btn-toggle">'
        content += '<button id="btn-open' + sensor['id'] + '" style="height:100px;width:180px;" type="button" class="btn btn-default btn-lg" onclick="switch_open(' + sensor['id'] + ')"><span class="glyphicon glyphicon-play"></span></button>'
        content += '<button id="btn-close' + sensor['id'] + '" style="height:100px;width:180px;" type="button" class="btn btn-primary btn-lg active" onclick="switch_close(' + sensor['id'] + ')"><span class="glyphicon glyphicon-pause"></span></button>'
        content += '</div></center></div></div>'
    } else if(sensor['type'] == 'n') {
        content += '<div class="box-header"><h3 class="box-title">Latest 20</h3>'
        content += '<div class="box-tools pull-right"><a href="{% url "PiApp.views.sensor_data_view" %}?sensor_id=' + sensor['id']
        content += '" style="color:#428bca;" )="">more here</a></div>'
        content += '</div>'
        content += '<div class="box-body chart-responsive""><div class="chart" id="revenue-chart-'+ sensor['id'] + '" style="height: 250px;"></div></div></div>'
    } else if(sensor['type'] == 'p') {
        content += '<div class="box-header"><h3 class="box-title">Latest 20</h3>'
        content += '<div class="box-tools pull-right"><a href="{% url "PiApp.views.sensor_data_view" %}?sensor_id=' + sensor['id']
        content += '" style="color:#428bca;" )="">more here</a></div>'
        content += '</div>'
        content += '<div class="box-body">'
        content += '<div class="carousel slide" id="carousel-506941">\
                        <div sensor_id=' + sensor['id'] + ' class="carousel-inner">\
                        </div>\
                        <a class="left carousel-control" href="#carousel-506941" data-slide="prev">\
                            <span class="glyphicon glyphicon-chevron-left"></span>\
                        </a>\
                        <a class="right carousel-control" href="#carousel-506941" data-slide="next">\
                            <span class="glyphicon glyphicon-chevron-right"></span>\
                        </a>\
                    </div>'
        content += '</div></div>'         
    }


    if(sensor['type'] == 's') {
        content += '<div style="margin-top:15px; margin-bottom:10px;">&nbsp <div class="align-right"><a onclick="show_callback(' + sensor['id'] + ')">+ add callback</a></div><div class="align-left"><b>Callback</b><a href="{% url "PiApp.views.home_help_view" %}#callback">(Help)</a></div></div>' 

        content += '<form style="display:none;" sensor_id=' + sensor['id'] + ' sensor_type=' + sensor['type'] + '>'
        content += '<div class="form-group"><label>Callback file</label>'                  
        content += '<div class="input-group input-group-sm"><input class="form-control" maxlength="120" name="callback" type="text" value="">'
        content += '<span class="input-group-btn"><button class="btn btn-primary btn-flat btn-callback" type="button" onclick="submit_callback(' + sensor['id'] + ')">Submit</button></span></div></div>'
    }
   

    if(sensor['type'] == 'n') {
        content += '<div style="margin-top:15px; margin-bottom:10px;">&nbsp <div class="align-right"><a onclick="show_callback(' + sensor['id'] + ')">+ add callback</a></div><div class="align-left"><b>Callback</b><a href="{% url "PiApp.views.home_help_view" %}#callback">(Help)</a></div></div>' 

        content += '<form style="display:none;" sensor_id=' + sensor['id'] + ' sensor_type=' + sensor['type'] + '>'
        content += '<div class="form-group"><label>Conditions</label>'
        content += '<div class="row">'
        content += '<div class="col-md-2">'
        content += '<select class="form-control" name="callback_condition"><option value="lt">&lt</option><option value="lte">&lt=</option><option value="gt">&gt</option><option value="gte">&gt=</option><option value="ne">!=</option><option value="e">==</option></select>'
        content += '</div><div class="col-md-2">'
        content += '<input class="form-control" maxlength="120" name="callback_value" type="text" value="">'
        content += '</div>'
        content += '</div>'
        content += '</div>'

        content += '<div class="form-group"><label>Callback file</label>'                  
        content += '<div class="input-group input-group-sm"><input class="form-control" maxlength="120" name="callback" type="text" value="">'
        content += '<span class="input-group-btn"><button class="btn btn-primary btn-flat btn-callback" type="button" onclick="submit_callback(' + sensor['id'] + ')">Submit</button></span></div></div>'
  
    } 

    content += '</form>' 
    content += '</div></div>'

    content += '</div></div>';
                                                       
                                    
    return content;
}
function remove_sensor(get_id){
    if(confirm('Sure?')) {
        $.getJSON("/API/sensor/" + get_id + "/remove" ,  {}, 
            function(data){
                if(data['msg'] != 'ok') {
                    alert('failed');
                } else {
                    window.location.href=("");  
                }                  
        });
    }
}
function edit_sensor(get_id){
    window.location.href=("{% url 'PiApp.views.edit_sensor_view' %}?sensor_id=" + get_id);
}
function switch_open(get_id){
    $("#btn-close" + get_id).attr('class', 'btn btn-default btn-lg');
    $("#btn-open" + get_id).attr('class', 'btn btn-primary btn-lg active');    
    $.getJSON("/API/sensor/" + get_id + '/datapoint' ,  {value : 1}, 
        function(data){
            if(data['msg'] != 'ok') {
                alert('failed');
            }                
    });
}
function switch_close(get_id){
    $("#btn-close" + get_id).attr('class', 'btn btn-primary btn-lg active');
    $("#btn-open" + get_id).attr('class', 'btn btn-default btn-lg'); 
    $.getJSON("/API/sensor/" + get_id + '/datapoint' ,  {value : 0}, 
        function(data){
            if(data['msg'] != 'ok') {
                alert('failed');
            }                 
    });  
}
function switch_refresh(get_id){
    $.getJSON("/API/sensor/" + get_id + '/datapoint/get/' ,  { }, 
        function(data){
            if(data['msg'] != 'ok') {
                alert('failed');
            } else {
                if(data['value'] == 1) {
                    $("#btn-close" + get_id).attr('class', 'btn btn-default btn-lg');
                    $("#btn-open" + get_id).attr('class', 'btn btn-primary btn-lg active');  
                } else {
                    $("#btn-close" + get_id).attr('class', 'btn btn-primary btn-lg active');
                    $("#btn-open" + get_id).attr('class', 'btn btn-default btn-lg');                                          
                }
                    
            }               
    });  
}
function curvet_refresh(get_id, unit){
    $.getJSON("/API/sensor/" + get_id + '/datapoint/history/',  { }, 
        function(data2){
            if(data2['msg'] != 'ok') {
                alert('failed');
            } else {
                var area = new Morris.Area({
                    element: "revenue-chart-" + get_id,
                    resize: true,
                    data: data2['datapoint'],
                    xkey: 'key',
                    ykeys: ['value'],
                    labels: ['value'],
                    // xLabels: [''],
                    postUnits : unit,
                    lineColors: ['#3c8dbc'],
                    hideHover: 'auto',
                });                              
            }               
    });                     
}
function img_refresh(get_id){
    $.getJSON("/API/sensor/" + get_id + '/datapoint/history/',  {}, 
        function(data){
            if(data['msg'] != 'ok') {
                // alert('failed');
            } else {
                for(var n=0; n < data['datapoint'].length; n++){
                    var content;
                    if(n == 0) {
                        content = '<div class="item active">'                        
                    }
                    else{
                        content = '<div class="item">'                             
                    }                  
                    content += '<center><img src="' + data['datapoint'][n]['value'] + '"></center>\
                                <div class="carousel-caption">\
                                    <h4 style="color:#fff;">Time</h4>\
                                    <p style="color:#fff;">' + data['datapoint'][n]['key'] + '</p> \
                                </div>\
                              </div>' 
                    $('.carousel-inner[sensor_id=' + get_id + ']').append(content);   
                }                                
            }               
    });                     
}
function submit_callback(get_id){
    if($("form[sensor_id=" + get_id + "]").attr("sensor_type")=='s') {
        callback_file_ = $("form[sensor_id=" + get_id + "] input[name='callback']").val();
        $.getJSON("/API/sensor/" + get_id + '/add_callback',  {callback_file : callback_file_}, 
            function(data){
                if(data['msg'] != 'ok') {
                    alert('failed');
                }          
        });          
    } else {
        callback_file_ = $("form[sensor_id=" + get_id + "] input[name='callback']").val();
        callback_value_ = $("form[sensor_id=" + get_id + "] input[name='callback_value']").val();
        callback_condition_ = $("form[sensor_id=" + get_id + "] select[name='callback_condition']").val();

        $.getJSON("/API/sensor/" + get_id + '/add_callback' , {callback_file : callback_file_, callback_value :callback_value_, callback_condition : callback_condition_,}, 
            function(data){
                if(data['msg'] != 'ok') {
                    alert('failed');
                }          
        });          
    }

}
function callback_refresh(get_id){
    if($("form[sensor_id=" + get_id + "]").attr("sensor_type")=='s') {
        $.getJSON("/API/sensor/" + get_id + '/get_callback',  { }, 
            function(data){
                if(data['msg'] != 'ok') {
                    alert('failed');
                } else {
                    $("form[sensor_id=" + get_id + "] input[name='callback']").val(data['callback_file']);
                }          
        });          
    } else {
        $.getJSON("/API/sensor/" + get_id + '/get_callback',  { },
            function(data){
                if(data['msg'] != 'ok') {
                    alert('failed');
                } else {
                    $("form[sensor_id=" + get_id + "] input[name='callback']").val(data['callback_file']);
                    $("form[sensor_id=" + get_id + "] input[name='callback_value']").val(data['callback_value']);
                    $("form[sensor_id=" + get_id + "] select[name='callback_condition']").val(data['callback_condition']);
                }             
        });          
    }

}
function show_callback(get_id){
    $("form[sensor_id=" + get_id + "]").css("display", "block"); 
}

</script>  
{% endblock %}

{% block on_ready%}    
{% endblock %}

{% block content %} 
<div class="row">      
    <div class="col-md-12">
        <div class="box box-solid box-navy ">
            <div class="box-header">
                <i class="fa fa-wrench"></i>
                <h3 class="box-title">Device</h3>
                <div class="box-tools pull-right">
                    {% for device in device_all %}    
                        <button id="btn-{{ device.id }}" class="btn btn-navy" onclick="get_data({{ device.id }})">{{ device.name }}</button>
                    {% endfor %}
                </div>                
            </div><!-- /.box-header -->
            
            <div class="box-body" id="device-body" style="display:none;">
                <div class="row">
                    <div class="col-md-6">
                        <h4 id="device-name"  data-id="1" class="page-header header-bold">                        
                        </h4>                        
                    </div>
                    <div class="col-md-6">
                        <div id='device-btn' class="btn-group" style="float:right;">

                        </div>
                    </div>
                </div>
                <table class="table table-striped table-responsive">
                    <tbody>
                        <tr>
                            <th>X</th>
                            <th>Y</th>
                            <th>Location</th>
                            <th>ID</th>
                        </tr>
                        <tr>
                            <th id="device-x"></th>
                            <th id="device-y"></th>
                            <th id="device-location"></th>
                            <th id="device-id"></th>
                        </tr>
                    </tbody>
                </table>

                <div style="">
                    <h4 class="page-header header-bold">
                        Sensor          
                        <small>Manage the device's sensor.</small>               
                    </h4>                    
                </div>
                <div style="padding-bottom:20px;">
                    <button class="btn btn-success" onclick="add_sensor()"><i class="fa fa-plus"></i> add a sensor</button>
                </div>
                <div id="sensor-content">
                    
                </div>
                <div class="alert alert-warning alert-dismissable" style="margin-top:32px;margin-left:10px;display:None;">
                    <i class="fa fa-warning"></i>
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    No Sensor find！
                </div>
            </div>

            <div class="box-footer">
            </div>
        </div>
    </div>
</div>  


{% endblock %}